package org.example.thread;

import javax.swing.*;
import java.awt.*;

public class FrameMoveThread extends Thread{

    private JFrame frame;
    private boolean loop = true;
    private int speedY = 5;
    private int speedX = 5;
    private double screenSizeHeight;
    private double screenSizeWidth;
    private int frameHeight;
    private int frameWidth;

    public FrameMoveThread(JFrame frame) {
        this.frame = frame;

        //获取当前屏幕大小
        getScreenSize();
    }

    private void getScreenSize() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        screenSizeWidth = screenSize.getWidth();
        screenSizeHeight = screenSize.getHeight();
    }


    @Override
    public void run() {
        while (loop){
            //更新窗口大小
            getFrameSize();
            //开始移动
            frameMoveUpAndDown();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }

    private void getFrameSize() {
        frameWidth = frame.getWidth();
        frameHeight = frame.getHeight();
    }

    public void frameMoveUpAndDown(){
        Point frameLocation = this.frame.getLocation();
        int localX = frameLocation.x;
        int localY = frameLocation.y;
        if (localX <= 0 || localX + frameWidth >= screenSizeWidth){
            speedX = -speedX;
        }
        if (localY <= 0 || localY + frameHeight >= screenSizeHeight){
            speedY = -speedY;
        }
        this.frame.setLocation(localX + speedX,localY + speedY);


    }



    public synchronized void stopMove(){
        loop = false;

    }
}
